/* 
    Project     : 48c6c450f1a4a0cc53d9585dc0fee742
    Created on  : Mar 16, 2013, 11:29:15 PM
    Author      : Truong Khuong - khuongxuantruong@gmail.com
    Description :
        Purpose of the stylesheet follows.
*/
var CONGIFS={
    GRID_ELEM:'#jqxGrid_Backend'
};
var Wallpaper=function(){
    var me=this;
    this.init=false;
    this.datafields=[
        { name  :   'albu_id' ,type :   'int'},
        { name  :   'albu_title' },
        { name  :   'albu_alias' },
        { name  :   'albu_status', type : 'bool' },
        { name  :   'albu_insert' },
        { name  :   'albu_update' },
        { name  :   'albu_desc' }
    ],
    this.columns=[
        { text: 'Title'     , dataField: 'albu_title'       ,filterable:false },
        { text: 'Status'    , dataField: 'albu_status'      ,width:80,filterable:false ,columntype:'checkbox',threestatecheckbox:false,filtertype:'bool'},
        { text: 'Insert'    , dataField: 'albu_insert'      ,width:120,filterable:false ,cellsformat:'yyyy-MM-dd HH:mm:ss'},
        { 
            text: '#'        , dataField: 'albu_id'          ,width:60,filterable:false ,sortable: false,
            cellsrenderer : function (row, column, value) {
                var str="<span style='margin: 4px; float: left;'>";
                if(value && value>0){
                    try{
                        //value = $.parseJSON(value);
                        str+="\
                            <div onclick=\"Wallpaper1.loadAlbum('"+value+"');\" \
                            class='w-16 h-16 f-l m-r-4 c-s-p hover-50 edit-icon' title='Edit'></div>\
                        ";
                        str+="\
                            <div onclick=\"Wallpaper1.DeleteItem('"+value+"');\" \
                            class='w-16 h-16 f-l m-r-4 c-s-p hover-50 del-icon' title='Delete'></div>\
                        ";
                    }catch(e){ErrorMsg(e.message);}
                }
                str+="</span>";
                return str;
            }
        },
    ],
    this.source ={
        datatype: "json",type : "POST",
        datafields: this.datafields,
        url: base_url+'backend/wallpaper/binding',
        filter      : function(){ $(CONGIFS.GRID_ELEM).jqxGrid('updatebounddata', 'filter'); },
        sort        : function(){ $(CONGIFS.GRID_ELEM).jqxGrid('updatebounddata'); },
        root        : 'rows',
        beforeprocessing: function(data){ me.source.totalrecords = data.total_rows; }
    },
    this.dataAdapter = new $.jqx.dataAdapter(this.source, {
        loadError: function(xhr, status, error){
            ErrorMsg("<b>Status</b>:"+xhr.status+"<br/><b>ThrownError</b>:"+error+"<br/>");
        }
    }),
    this.grid_element='#jqxGrid_Backend';
    this.OnInit=function(){
        try{
            $(CONGIFS.GRID_ELEM).jqxGrid({
                rendergridrows: function(obj){
                    return obj.data;    
                },ready: function () {
                    //Categories.Filter('cate_type','news');
                },
                width: '100%',//height:'100%',
                source: this.dataAdapter,
                theme: theme,sortable: true,
                //filterable: true,
                //autoshowfiltericon: true,
                //showfilterrow: true,
                showemptyrow: true,
                virtualmode:false,
                columns: this.columns
            });
        }catch(e){
            ErrorMsg(e.message);
        }
    };
    this.AddAlbumItems=function(files,albumid){
            new backend({
                url         :   base_url+"backend/wallpaper/addalbumitems",
                data        :   {
                    Images  :   files,
                    AlbumId :   albumid
                },
                callback    :   function(rsdata){
                    if(rsdata.result<0){
                        bckdialog({type:'error'}).open(rsdata.message);
                    }else{
                        NoticeMsg(rsdata.message);
                    }
                }
            }).call();
    };
    this.AddAlbum=function(){
            new backend({
                url         :   base_url+"backend/wallpaper/addalbum",
                data        :   {
                    albu_id :   $('#albu_id').val(),
                    params  :   $('#albu_frm').serializeObject()
                },
                callback    :   function(rsdata){
                    if(rsdata.result<0){
                        bckdialog({type:'error'}).open(rsdata.message);
                    }else{
                        //NoticeMsg(rsdata.message);
                        $(CONGIFS.GRID_ELEM).jqxGrid('updatebounddata');
                        $('#jqxTabBackend').jqxTabs('next');
                        if(rsdata.albu_id!=undefined)$('#albu_id').val(rsdata.albu_id);
                        
                    }
                }
            }).call();
    };
    this.AddAlbumItems = function(){
        var imgs=$('#txtChooseImage').html();
        if(imgs=='DblClick to choose image.')return;
        imgs=imgs.split('\n');
        var albu_imgs=new Array();
        for (var i = 0; i < imgs.length; i++){
            if(imgs[i]!=""){
                albu_imgs.push(imgs[i]);
            }

        }
        if(albu_imgs.length>0){
            new backend({
                url         :   base_url+"backend/wallpaper/addalbumitems",
                data        :   {
                    albu_id :   $('#albu_id').val(),
                    albu_imgs  :   albu_imgs
                },
                callback    :   function(rsdata){
                    if(rsdata.result<0){
                        bckdialog({type:'error'}).open(rsdata.message);
                    }else{
                        NoticeMsg(rsdata.message);
                        $('#jqxTabBackend').jqxTabs('next');
                        if(rsdata.albu_id!=undefined)$('#albu_id').val(rsdata.albu_id);
                        for (var i = 0; i < albu_imgs.length; i++){
                            var thumb=albu_imgs[i];//.replace('/data/','/data/thumbs/')
                            $('#lstAlbumItems').append(
                                '<div class="grid_2 h-g-2 b-d-c-ccc m-4 p-r hide-child">\
                                    <div class="p-a t-0 r-0  chide close-icon"></div>\
                                    <img class="album-img-thumb"\
                                        data-source="'+thumb+'"\
                                        onerror="this.src = \'/libraries/images/22/picture.png\'" class="m-0-a d-p-b p-t-2"\
                                        src="'+thumb+'">\
                                </div>');
                        }
                    }
                }
            }).call();
        }
        $('#txtChooseImage').html('DblClick to choose image.');
    };
    this.loadAlbum = function(albu_id){
        new backend({
            url         :   base_url+"backend/wallpaper/loadalbum",
            data        :   {
                albu_id :   albu_id
            },
            callback    :   function(rsdata){
                if(rsdata.result<0){
                    bckdialog({type:'error'}).open(rsdata.message);
                }else{
                    $('#albu_id').val(rsdata.album.albu_id),
                    $('#txtAlbumName').val(rsdata.album.albu_title);
                    $('#txtAlbumDesc').val(rsdata.album.albu_desc);
                    $('#lstAlbumItems').html('');
                    for (var i = 0; i < rsdata.album.imgs.length; i++){
                        var thumb=rsdata.album.imgs[i].data_source;//.replace('/data/','/data/thumbs/')
                        $('#lstAlbumItems').append(
                            '<div class="grid_2 h-g-2 b-d-c-ccc m-4 p-r hide-child albu_item_'+rsdata.album.imgs[i].data_id+'">\
                                <div class="p-a t-0 r-0 chide close-icon" onclick="Wallpaper1.deleteAlbumItem('+rsdata.album.imgs[i].data_id+')"></div>\
                                <img class="album-img-thumb"\
                                    data-source="'+thumb+'"\
                                    onerror="this.src = \'/libraries/images/22/picture.png\'" class="m-0-a d-p-b p-t-2"\
                                    src="'+thumb+'">\
                            </div>');
                    }
                }
            }
        }).call();
    };
    this.deleteAlbumItem=function(data_id){
        new backend({
            url         :   base_url+"backend/wallpaper/deletealbumitem",
            data        :   {
                data_id :   data_id
            },
            callback    :   function(rsdata){
                if(rsdata.result<0){
                    bckdialog({type:'error'}).open(rsdata.message);
                }else{
                    $('.albu_item_'+data_id).remove();
                }
            }
        }).call();
    };
    this.DeleteItem=function(Id){
        ConfirmMsg(function(){
            backend_delete('album','album','albu',Id,function(){
                $(CONGIFS.GRID_ELEM).jqxGrid('updatebounddata');
                $("#bckconfirmdialog").dialog('close');
            });
        },'These items will be permanently deleted and cannot be recovered. Are you sure ?','Delete');
    };
    this.Refresh=function(){
        $(CONGIFS.GRID_ELEM).jqxGrid('updatebounddata');
    };
    this.MakeRandomAlbum=function(){
        var sw=$("#slider_image_width").jqxSlider('val');
        var sh=$("#slider_image_height").jqxSlider('val');
        var imgs=new Array();
        imgs=$('#lstAlbumItems .album-img-thumb').map(function(){
            return this.src;
        });
        var str='';
        for(var i=0;i<imgs.length;i++){
            var width=sw,height=sh;
            var v=Math.floor(Math.random()*7)+1;
            var h=Math.floor(Math.random()*7)+1;
            var r=Math.floor(Math.random()*255);
            var g=Math.floor(Math.random()*255);
            var b=Math.floor(Math.random()*255);
            if(v<=2)width=(width*2)+4;
            if(v<=2 && h<=2)height=(height*2)+4;
            str+='<div class="item" style="position:absolute;display:inline-block;background: rgb('+r+','+g+','+b+');width:'+width+'px;height:'+height+'px"'+((v<=2)?' data-ss-colspan="2"':'')+'><img style="display:block;width:100%;height:100%;" src="'+imgs[i]+'"/></div>';
        }
        $('#album_preview').html(str);
        $('#album_preview').shapeshift({
            minColumns: 3,
            enableDrag:false,
            enableCrossDrop:false,
            enableResize: true,
            enableTrash: false,
            gutterX: 4,
            gutterY: 4,
            paddingX: 4,
            paddingY: 4
        });
    };
};
var Wallpaper1=new Wallpaper();

var wizard=(function () {
        //Adding event listeners
        var _addHandlers = function () {
            $('#txtAlbumName').keyup(function () {
                //wizard.validate(true);
            });
            $('#txtAlbumName').change(function () {
                //wizard.validate(true);
            });
            $('#txtAlbumDesc').change(function () {
                //wizard.validate(true);
            });
            $('#txtAlbumDesc').keyup(function () {
                //wizard.validate(true);
            });
            $('#nextButtonInfo').click(function () {
                wizard.validate(true);
                
                
            });
        };
        return {
            //Initializing the wizzard
            init: function () {
                _addHandlers();
                this.validate();
                this.showHint('Validation hints.');
                
            },
            //Validating all wizard tabs
            validate: function (notify) {
                if (!this.firstTab(notify)) {
                    $('#jqxTabBackend').jqxTabs('disableAt', 1);
                    return;
                } else {
                    $('#jqxTabBackend').jqxTabs('enableAt', 1);
                    Wallpaper1.AddAlbum();
                }
//                if (!this.secondTab(notify)) {
//                    $('#jqxTabs').jqxTabs('disableAt', 2);
//                    return;
//                } else {
//                    $('#jqxTabs').jqxTabs('enableAt', 2);
//                }
            },
            //Displaying message to the user     
            showHint: function (message, selector) {
                if (typeof selector === 'undefined') {
                    selector = '.hint';
                }
                if (message === '') {
                    message = 'You can continue.';
                }
                $(selector).html('<strong>' + message + '</strong>');
            },
            //Validating the first tab
            firstTab: function (notify) {
                var username = $('#txtAlbumName').val(),
                    password = $('#txtAlbumDesc').val(),
                    message = '';
                if (username.length < 3) {
                    message += 'You have to enter valid album name. <br />';
                }
                if (password.length < 3) {
                    message += 'You have to enter valid album desc. <br />';
                }
                if (message !== '') {
                    if (notify) {
                        this.showHint(message, '#hintSection');
                    }
                    return false;
                }
                this.showHint('You can continue.', '#hintSection');
                return true;
            },
        };
    }());
$(document).ready(function () {
        
        $("#jqxTabBackend").jqxTabs({
            theme: 'metro', height: 'auto',  scrollable: true, 
            selectionTracker: true, animationType: 'fade',keyboardNavigation: false,
            initTabContent: function(tab) {
                switch (tab) {
                    case 0:
                        Wallpaper1.OnInit();
                        wizard.init();
                        break;
                    case 1:
                        $('#slider_image_width').jqxSlider({ min: 4, max: 240, mode: 'fixed', ticksFrequency: 20, width: 240, value: 80, theme: theme, showButtons: false });
                        $('#slider_image_height').jqxSlider({ min: 4, max: 240, mode: 'fixed', ticksFrequency: 20, width: 240, value: 80, theme: theme, showButtons: false });
                        $('#slider_album_width').jqxSlider({ min: 320, max: 720, mode: 'fixed', ticksFrequency: 20, width: 240, value: 480, theme: theme, showButtons: false })
                        .on('slideEnd', function (e) {
                            $('#album_preview').css('width',e.args.value);
                        });
                        break;
                    case 2:
                        break;
                    case 3:
                        break;
                    case 4:
                        
                        break;
                    case 5:
                        
                        break;
                }
            }
        });
        $( "#txtChooseImage" ).dblclick(function() {
            openKCFinderMulti(function(files){
                var str='';
                for (var i = 0; i < files.length; i++){
                    str += files[i] + "\n";
                }
                $('#txtChooseImage').html(str);
                //Wallpaper1.AddAlbumItems(files);
            })
        });
        $('#btnAddAlbumItem').click(function(){
            Wallpaper1.AddAlbumItems();
        });
});
